import json
from enum import Enum
from unicodedata import decimal

import requests

from models.RedisOperation import RedisClient


class NotificationsEnum(Enum):
    ReportCompleted = 'rtZ9_NWBT9KS4bahppIn7qbFj8ObsSisjgJn_cpqf84'


class Notification(object):
    r = RedisClient()

    def __init__(self):
        self.token = self.getGZHToken()
        self.url = f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={self.token}'

    def getGZHToken(self):
        token = self.r.GetGZHToken()
        if token:
            return token
        url = 'https://api.weixin.qq.com/cgi-bin/stable_token'
        data = {
            "grant_type": "client_credential",
            "appid": "wxfbf829ced26521ae",
            "secret": "4987a453c152a4fb2eb902344cd524c3"
        }
        res = requests.post(url=url, data=json.dumps(data), verify=False)
        if res.status_code == 200:
            res_data = json.loads(res.text)
            access_token = res_data['access_token']
            expire = res_data['expires_in']
            self.r.setGZHToken(access_token, expire)
            return access_token
        else:
            print(res.text)
            return None

    def ReportCompletedNotification(self, openid, title, create_time, rate):
        data = {
            "touser": openid,
            "template_id": NotificationsEnum.ReportCompleted.value,
            "miniprogram": {
                "appid": "wxe714527bc5c7ec08",
                "pagepath": "pages/search/search"
            },
            "data": {
                "thing11": {
                    "value": title
                },
                "time4": {
                    "value": create_time
                },
                "thing6": {
                    "value": rate
                }
            }
        }
        res = requests.post(self.url, data=json.dumps(data))
        if res.status_code == 200:
            print(res.text)
        else:
            print(res.text)


if __name__ =='__main__':
    notification = Notification()
    notification.ReportCompletedNotification('oWInjwiOIKeLxKjC1vbkSytIkbXc','123','2024-04-05 13:39', '100%')